<template>
  <div class="app-container">
    <el-scrollbar class="form-scrollbar">
      <el-form
        ref="form"
        class="form-company"
        :rules="rules"
        :model="userInfo"
        label-width="110px"
      >
        <el-card v-loading="infoLoading" shadow="never">
          <div slot="header" class="clearfix">
            <span>{{ $t('userCenter.myProfile') }}</span>
            <el-button class="!ml-5 !p-0" type="text" @click="editPassword"
              >{{ $t('userCenter.changePassword') }}
            </el-button>
          </div>
          <div class="basic-data">
            <!--            <div class="tip-text">-->
            <!--              基本信息-->
            <!--            </div>-->
            <div class="basic_info">
              <el-form-item :label="$t('common.username')">
                <el-input
                  v-model="userInfo.username"
                  style="max-width: 400px"
                  disabled
                />
              </el-form-item>
              <el-form-item
                :label="$t('common.truename')"
                prop="name"
                class="truename"
              >
                <el-input
                  v-model="userInfo.name"
                  class="max-w-100"
                  @input="checkTrim('name')"
                  autocomplete="off"
                >
                  <el-button slot="append" @click="updateName">{{
                    $t('common.update')
                  }}</el-button>
                </el-input>
              </el-form-item>
              <el-form-item :label="$t('common.createTime')">
                <span>{{ userInfo.created }}</span>
              </el-form-item>
              <el-form-item :label="$t('common.expireTime')">
                <span>{{ userInfo.validity }}</span>
              </el-form-item>
            </div>

            <div class="basic_avatar">
              <div style="float: left; width: 300px">
                <el-form-item>
                  <el-upload
                    class="avatar-uploader"
                    :action="uploadAction"
                    :show-file-list="false"
                    :on-success="handleAvatarSuccess"
                    accept=".jpeg,.png,.jpg"
                    :before-upload="beforeAvatarUpload"
                  >
                    <img
                      v-if="userInfo.avatar"
                      :src="userInfo.avatar"
                      class="avatar"
                    />
                    <i v-else class="el-icon-plus avatar-uploader-icon" />
                  </el-upload>
                  <el-alert
                    class="h-7.5 !w-44.5"
                    :title="$t('common.maxImageSize', { size: '1M' })"
                    type="warning"
                    :closable="false"
                    show-icon
                  />
                </el-form-item>
              </div>
            </div>
          </div>
          <el-divider />
        </el-card>

        <el-card v-loading="infoLoading" shadow="never">
          <div slot="header">导出客户数据配置</div>
          <el-form-item
            label="导出客户数据前验证邮箱有效性"
            label-width="250px"
          >
            <el-switch
              v-model="userInfo.settings.validateEmailBeforeExport"
              active-text="开启"
              inactive-text="关闭"
            >
            </el-switch>
          </el-form-item>

          <el-form-item label="仅导出有效邮箱的客户" label-width="250px">
            <el-switch
              v-model="userInfo.settings.onlyExportValidEmails"
              active-text="开启"
              inactive-text="关闭"
            >
            </el-switch>
          </el-form-item>

          <el-button type="primary" class="!ml-60 !mb-2" @click="updateName">{{
            $t('common.save')
          }}</el-button>
        </el-card>
      </el-form>

      <el-dialog
        class="update-password"
        :title="$t('userCenter.changePassword')"
        :visible.sync="passwordState"
        width="500px"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        append-to-body
      >
        <el-form
          ref="formPassword"
          label-width="120px"
          :rules="rulePassword"
          v-loading="passwordLoading"
          :model="passwordInfo"
        >
          <el-form-item
            :label="$t('userCenter.oldPassword')"
            prop="originalPassword"
          >
            <el-input v-model="passwordInfo.originalPassword" />
          </el-form-item>
          <el-form-item :label="$t('userCenter.newPassword')" prop="password">
            <el-input v-model="passwordInfo.password" />
          </el-form-item>
          <el-form-item
            :label="$t('userCenter.repeatPassword')"
            prop="checkPassword"
          >
            <el-input v-model="passwordInfo.checkPassword" />
          </el-form-item>
        </el-form>

        <span slot="footer" class="dialog-footer">
          <el-button
            type="primary"
            :disabled="passwordLoading"
            @click="updatePassword"
            >{{ $t('common.update') }}</el-button
          >
          <el-button @click="passwordState = false">{{
            $t('common.cancel')
          }}</el-button>
        </span>
      </el-dialog>
    </el-scrollbar>
  </div>
</template>

<script>
import { UserModule } from '@/store/modules/user'
import common from '@/utils/common'
import { postAction } from '@/api/common'

export default {
  name: 'userCenter',
  data() {
    const validatePass = (rule, value, callback) => {
      if (value.length < 6 || value.length > 16) {
        callback(
          new Error(
            this.$t('userCenter.passwordLengthBetween', { min: 6, max: 16 })
          )
        )
      } else if (value == this.passwordInfo.originalPassword) {
        callback(new Error(this.$t('userCenter.passwordCantSameWithOrigin')))
      }
      this.$refs.formPassword.validateField('confirmPassword')
      callback()
    }
    const validatePass2 = (rule, value, callback) => {
      console.log(value, this.passwordInfo)
      if (value === '') {
        callback(new Error(this.$t('userCenter.inputPasswordAgain')))
      } else if (value == this.passwordInfo.originalPassword) {
        callback(new Error(this.$t('userCenter.passwordCantSameWithOrigin')))
      } else if (value !== this.passwordInfo.password) {
        callback(new Error(this.$t('userCenter.passwordNotSame')))
      } else {
        callback()
      }
    }
    return {
      uploadAction: '/api/UserCompany/UploadAvatarImg',
      userInfo: {
        username: '',
        name: '',
        avatar: '',
        created: '',
        validity: '',
        settings: {},
      },
      infoLoading: false,
      passwordInfo: {
        originalPassword: '',
        password: '',
        checkPassword: '',
      },
      rules: {
        name: [
          {
            required: true,
            message: this.$t('common.enter', [this.$t('common.truename')]),
            trigger: 'change',
          },
        ],
      },
      passwordLoading: false,
      passwordState: false,
      rulePassword: {
        originalPassword: [
          {
            required: true,
            message: this.$t('common.enter', [this.$t('common.password')]),
            trigger: 'change',
          },
          {
            min: 6,
            max: 16,
            message: this.$t('userCenter.passwordLengthBetween', {
              min: 6,
              max: 16,
            }),
            trigger: 'blur',
          },
        ],
        password: [{ validator: validatePass, trigger: 'blur' }],
        checkPassword: [{ validator: validatePass2, trigger: 'blur' }],
      },
    }
  },
  created() {
    this.init()
  },
  methods: {
    async init() {
      this.infoLoading = true
      const { data } = await postAction({}, 'UserCompany/GetUserCenterInfo')
      // console.log(data)
      this.userInfo = data
      this.infoLoading = false
    },
    checkTrim(obj) {
      this.userInfo[obj] = common.checkAllTrim(this.userInfo[obj])
    },
    handleAvatarSuccess(res, file) {
      // eslint-disable-next-line eqeqeq
      if (res.code == 20000) {
        this.userInfo.avatar = res.data
        UserModule.SET_AVATAR(res.data)
        this.infoLoading = false
      } else {
        this.$message.error(res.message)
        this.infoLoading = false
      }
    },
    beforeAvatarUpload(file) {
      this.infoLoading = true
      const isType =
        file.type === 'image/jpeg' ||
        file.type === 'image/jpg' ||
        file.type === 'image/png'
      const isLt1M = file.size / 1024 / 1024 < 1
      if (!isType) {
        this.$message.error(this.$t('userCenter.uploadAvatarFormatLimit'))
        this.infoLoading = false
      }
      if (!isLt1M) {
        this.$message.error(
          this.$t('userCenter.uploadAvatarSizeLimit', { size: '1MB' })
        )
        this.infoLoading = false
      }
      return isType && isLt1M
    },
    async updateName() {
      await postAction(
        { name: this.userInfo.name, settings: this.userInfo.settings },
        'UserCompany/SubUserCenterInfo'
      )
      UserModule.setName(this.userInfo.name)
      UserModule.setSettings(this.userInfo.settings)
      this.$notify({
        title: this.$t('common.success'),
        message: this.$t('common.operationSuccess'),
        type: 'success',
        duration: 2000,
      })
    },
    editPassword() {
      this.passwordInfo = {
        originalPassword: '',
        password: '',
        checkPassword: '',
      }
      this.passwordState = true
    },
    updatePassword() {
      this.$refs.formPassword.validate(async (valid) => {
        // form验证
        if (valid) {
          this.passwordLoading = true
          await postAction(
            this.passwordInfo,
            'UserCompany/SubUserCenterPassword'
          )
          this.passwordLoading = false
          this.passwordState = false
          this.$notify({
            title: this.$t('common.success'),
            message: this.$t('common.operationSuccess'),
            type: 'success',
            duration: 2000,
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
  },
}
</script>

<style scoped>
.form-scrollbar {
  height: calc(100vh - 75px);
}

.form-company {
  min-width: 700px;
}

.app-container {
  height: calc(100vh - 65px);
}

.el-card__footer {
  bottom: 0;
  padding: 18px 20px;
  border-top: 1px solid #ebeef5;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
}

/deep/ .el-card__body {
  padding: 0;
}

.truename /deep/ .el-button {
  background-color: #409eff;
  color: #fff;
  border-top-left-radius: 0;
  border-bottom-left-radius: 0;
}

.truename /deep/ .el-button:hover {
  background-color: #66b1ff;
}

.avatar-uploader {
  width: 178px;
  height: 178px;
  border: 1px dashed #d9d9d9;
  border-radius: 10px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  background-color: #fbfdff;
}

.avatar-uploader:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.basic_info {
  float: left;
  /*min-height: 260px;*/
  width: 50%;
  min-width: 350px;
}

.basic_avatar {
  float: left;
  /*height: 300px;*/
  width: 50%;
  min-width: 510px;
}

.avatar-info {
  float: left;
  margin-top: 20px;
}

/deep/ .el-form-item {
  margin-bottom: 15px;
}

.avatar-info /deep/ .el-form-item {
  margin-bottom: 0;
  text-align: justify;
  text-align-last: justify;
}

.basic-data {
  padding: 20px 20px 10px 20px;
}

.basic-data:after {
  content: '020';
  display: block;
  height: 0;
  clear: both;
  visibility: hidden;
}

/deep/ .el-divider {
  margin: 0;
}

.tip-text {
  margin: 0 0 15px 10px;
  font-size: 15px;
}
.update-password /deep/ .el-dialog {
  margin-top: 30vh !important;
  min-width: 400px;
  width: 500px;
}

.update-password /deep/ .el-dialog__body {
  padding: 20px 20px 0 20px;
}
</style>
